package com.hcc.repository.gen.model;

import com.hcc.repository.annotation.Column;
import com.hcc.repository.annotation.Id;
import com.hcc.repository.annotation.IdType;
import com.hcc.repository.core.utils.StrUtils;
import lombok.Data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * ColumnMetadata
 *
 * @author hushengjun
 * @date 2023/9/20
 */
@Data
public class ColumnMetadata {

    private String name;
    private String comment;
    private String columnType;
    private String propType;
    private Class<?> javaType = Object.class;
    private Integer length;
    private boolean nullable;
    private boolean isPrimary = false;
    private boolean isAutoIncrement = false;

    public String getComment() {
        if (StrUtils.isEmpty(comment)) {
            return name;
        }
        return comment;
    }

    public String getPropName() {
        String propName = StrUtils.underlineToHump(name);
        if (StrUtils.isEmpty(propName)) {
            throw new IllegalArgumentException(String.format("无法将列名：[%s]转换为驼峰", name));
        }
        return StrUtils.firstCharToLowerCase(propName);
    }

    public String getPropClassName() {
        return javaType.getSimpleName();
    }

    public String getPropImportPackage() {
        return javaType.getName();
    }

    public List<String> getAnnotationImportPackage() {
        if (!needAnnotated()) {
            return Collections.emptyList();
        }
        List<String> packages = new ArrayList<>();
        if (isPrimary) {
            packages.add(Id.class.getName());
            packages.add(IdType.class.getName());
        } else {
            packages.add(Column.class.getName());
        }

        return packages;
    }

    public boolean needAnnotated() {
        if (isPrimary) {
            return true;
        }
        return name.startsWith("_") || name.endsWith("_");
    }

    public List<String> getAnnotations() {
        if (!needAnnotated()) {
            return Collections.emptyList();
        }
        List<String> annotations = new ArrayList<>();
        if (isPrimary) {
            if (isAutoIncrement) {
                annotations.add("@Id(value = \"" + name + "\", idType = IdType.AUTO)");
            } else {
                annotations.add("@Id(value = \"" + name + "\", idType = IdType.SPECIFY)");
            }
        } else {
            annotations.add("@Column(value = \"" + name + "\")");
        }
        return annotations;
    }

    public String getGetterMethodName() {
        return "get" + StrUtils.firstCharToUpperCase(getPropName());
    }

    public String getSetterMethodName() {
        return "set" + StrUtils.firstCharToUpperCase(getPropName());
    }

}
